<template>
  <div class="upload-file-wrap">
        <n-button v-if="fileUrl" style="margin-bottom: 10px" @click="fileTap(fileUrl)">{{
          nameStr
        }}</n-button>
    <n-upload
      :action="`${apiUrl}/upload`"
      :headers="uploadHeaders"
      @finish="handleLetterGuaranteeFinish"
      :show-file-list="false"
      :disabled="currentDisabled"
    >
      <n-button type="primary" ghost size="small">上传文件</n-button>
    </n-upload>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, inject, computed } from 'vue';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUser } from '@/store/modules/user';

  const userStore = useUser();
  const globSetting = useGlobSetting();
  const { apiUrl } = globSetting;
  const uploadHeaders = {
    Authorization: userStore.getToken,
  };

  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 文件最大10MB
    maxSize: {
      type: Number,
      default: 10,
    },
  });
  const nForm: any = inject('n-form'); // 使用inject函数注入属性
  const currentDisabled = computed(() => {
    return props.disabled || nForm.props.disabled;
  });
  const fileUrl = ref<string>(props.modelValue);
  const nameStr = computed(() => {
    const temp = fileUrl.value.split('/');
    return temp[temp.length - 1];
  });
  watch(
    () => props.modelValue,
    (newVal: string) => {
      fileUrl.value = props.modelValue;
    }
  );

  const handleLetterGuaranteeFinish = ({ file, event }) => {
    const res = JSON.parse((event?.target as XMLHttpRequest).response);
    fileUrl.value = res.data;
    emit('update:modelValue', fileUrl.value);
    return file;
  };

  const fileTap = (url) => {
    window.open(url, '_blank');
  };
</script>
